package com.lzj.server.common.controller;

import cn.dev33.satoken.annotation.SaIgnore;
import com.lzj.server.common.model.Attachment;
import com.lzj.server.common.model.FileInfo;
import com.lzj.server.common.service.AttachmentService;
import com.lzj.server.utils.Result;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.validation.constraints.NotBlank;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

/**
 * @author Lzj
 * @date 2025/5/6
 * @description 文件上传模块
 */
@SaIgnore
@Slf4j
@Tag(name = "文件上传模块")
@RestController
@RequestMapping("vimi/file")
public class FileUpLoadController {

    @Resource
    private AttachmentService attachmentService;


    @GetMapping("/init")
    @Operation(summary = "初始化分片上传任务")
    public Result<String> initUpload() {
        return Result.success(attachmentService.initUpload());
    }

    @PostMapping("/uploadPart")
    @Operation(summary = "分片上传文件")
    @Validated
    public Result<Boolean> uploadPart(@RequestPart MultipartFile file,
                                      @NotBlank(message = "上传ID不能为空") @RequestPart String uploadId,
                                      @RequestParam int partNumber) {
        return Result.success(attachmentService.uploadPart(file, uploadId, partNumber));
    }


    @PostMapping("/merge")
    @Operation(summary = "分片合并文件")
    public Result<Long> merge(@RequestBody FileInfo fileInfo) {
        return Result.success(attachmentService.merge(fileInfo));
    }


    @PostMapping("/upload")
    @Operation(summary = "直接上传文件", description = "上传文件到 OSS（S3 协议），返回附件 ID")
    public Result<Long> upload(
            @Parameter(description = "文件", required = true)
            @RequestPart(value = "file") MultipartFile file,
            @RequestParam(value = "duration", required = false)Integer duration) {
        return Result.success(attachmentService.updateFile(file));
    }

    @GetMapping("/get")
    @Operation(summary = "获取附件信息")
    public Result<Attachment> get(@RequestParam Long id) {
        return Result.success(attachmentService.getById(id));
    }
}
